package com.hctforgreen.greenservice;

import com.hctforgreen.greenservice.ExamSearchActivity.FreshExaminNumReceiver;
import com.hctforgreen.greenservice.ctr.DbTerminalExamController;
import com.hctforgreen.greenservice.ctr.HctController;
import com.hctforgreen.greenservice.model.AttrEntity;
import com.hctforgreen.greenservice.model.LoginResultEntity;
import com.hctforgreen.greenservice.model.MessageTopThirdEntity;
import com.hctforgreen.greenservice.ui.adapter.RecentTerminalDataListAdapter;
import com.hctforgreen.greenservice.ui.adapter.RecentTerminalExamListAdapter;
import com.hctforgreen.greenservice.ui.handler.RecentTerminalDataListHandler;
import com.hctforgreen.greenservice.ui.handler.RecentTerminalExamListHandler;
import com.hctforgreen.greenservice.ui.widget.TerminalDataTimePopupView;
import com.hctforgreen.greenservice.ui.widget.TerminalExameTypeListPopupView;
import com.hctforgreen.greenservice.ui.widget.TerminalExamineTimePopupView;
import com.hctforgreen.greenservice.ui.widget.TerminalLearningTypeListPopupView;
import com.hctforgreen.greenservice.utils.HctResult;
import com.hctforgreen.greenservice.utils.KeyboardUtil;
import com.hctforgreen.greenservice.utils.LoginResultStoreUtil;

import android.R.integer;
import android.content.BroadcastReceiver;
import android.content.Context;
import android.content.Intent;
import android.content.IntentFilter;
import android.os.Bundle;
import android.os.HandlerThread;
import android.util.Log;
import android.view.KeyEvent;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.Button;
import android.widget.EditText;
import android.widget.ImageButton;
import android.widget.LinearLayout;
import android.widget.ListView;
import android.widget.TextView;
import android.widget.Toast;

/**
 * 
 * @author 390694 终端培训--考试
 */
public class TerminalExamActivity extends ParentActivity implements
		OnClickListener {
	/**
	 * 广播，用于刷新考试记录数
	 */
	private FreshExaminNumReceiver mFreshExaminNumReceiver;
	public static final String FRESH_EXAMINE_NUM_ACTION = "fresh_examine_num_action";
	
	private TerminalExamActivity mSelfActivity;
	// 考试记录
	private LinearLayout lyt_exam_history;

	// 资料类别
	private Button btn_series;
	private TerminalExameTypeListPopupView mTypeListPopupView;
	/**
	 * 资料类别实体类
	 */
	private AttrEntity mCurrentFirstEntity;

	// 子类别
	private Button btn_child_series;
	private TerminalExameTypeListPopupView mChildTypeListPopupView;
	/**
	 * 子类别实体类
	 */
	private AttrEntity mCurrentSecondEntity;

	// 时间
	private Button btn_time;
	private TerminalExamineTimePopupView mThirdPopupView;
	/**
	 * 时间
	 */
	private MessageTopThirdEntity mSelectTimeEntity;

	// 标题
	//private EditText et_title_input;

	// 关键字、
	private EditText et_keyWord_input;

	// 搜索
	private Button btn_search;
	
	View convertView;
	// 最近上传考试的ListView
	ListView recentListView;

	@Override
	protected void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		setContentView(R.layout.activity_terminal_examination);
		mSelfActivity = this;
		initSkinLayout();
		initFreshExaminNumReceiver();
		initTitleButtonBar();
		initClickEdgehide();
		myFindViewById();
		initExamineHistoryNum();
		initWindow();
		
	}

	private void initWindow() {
		initRecentDataList();
		initExamineTypePopupView();
		initExamineChildTypePopupView();
		initTimePopupView();

		initSearchBtn();
	}

	/**
	 * 初始化考试记录数
	 */
	private void initExamineHistoryNum() {
		final TextView tv_historyNum = (TextView) findViewById(R.id.tv_exam_history);
		lyt_exam_history.setOnClickListener(new OnClickListener() {

			@Override
			public void onClick(View arg0) {
				Intent intent = new Intent(TerminalExamActivity.this,
						TerminalExamHistoryListActivity.class);
				startActivity(intent);
			}
		});
		new HandlerThread("getHistoryNum") {

			public void run() {
				LoginResultEntity loginResultEntity = LoginResultStoreUtil
						.get(mSelfActivity);

				String personIdString = loginResultEntity.personId;
				DbTerminalExamController dbTerminalExamController = new DbTerminalExamController(
						mSelfActivity);
				final int num = dbTerminalExamController
						.getExamPaperCount(personIdString);
				HctController controller = new HctController(mSelfActivity);

				try {
					final HctResult hctResult = controller
							.getPersonRecordNumForTerminal(personIdString);
					if (hctResult != null) {
						runOnUiThread(new Runnable() {

							@Override
							public void run() {
								int netNum = Integer.valueOf(hctResult.data
										+ "");
								netNum += num;
								tv_historyNum.setText(String.valueOf(netNum));

							}
						});
					}
				} catch (Exception e) {
					e.printStackTrace();
					runOnUiThread(new Runnable() {
						public void run() {
							tv_historyNum.setText(num + "");
						}
					});
				}
			};
		}.start();

	}
	
	/**
	 * 搜索最近上传资料
	 */
	private void initRecentDataList() {
		RecentTerminalExamListAdapter mTerminalExamListAdapter;

		RecentTerminalExamListHandler handler = new RecentTerminalExamListHandler(
				this, convertView);
		mTerminalExamListAdapter = new RecentTerminalExamListAdapter(
				recentListView, this, R.layout.layout_loading,
				R.layout.layout_reloading, handler);
	}
	

	/**
	 * 搜索
	 */
	private void initSearchBtn() {
				
		btn_search.setOnClickListener(new OnClickListener() {

			@Override
			public void onClick(View v) {

				KeyboardUtil keyboardUtil = new KeyboardUtil();
				keyboardUtil.hideSoftKeyboard(v);
				
				String keyWordString = et_keyWord_input.getText().toString().trim();
				//String titleWordString = et_title_input.getText().toString().trim();

				Intent intent = new Intent(TerminalExamActivity.this,
						TerminalExamineListActivity.class);

				String studyTypeId = mCurrentFirstEntity == null ? ""
						: mCurrentFirstEntity.id;
				intent.putExtra("studyTypeId", studyTypeId);
				
				String childTypeId = mCurrentSecondEntity == null ? ""
						: mCurrentSecondEntity.id;
				intent.putExtra("childTypeId", childTypeId);
				
				String time = mSelectTimeEntity == null ? ""
						: mSelectTimeEntity.dateType;
				intent.putExtra("time", time);
				//intent.putExtra("themeWord", titleWordString);
				intent.putExtra("keyWord", keyWordString);
				startActivity(intent);

			}
		});

	}

	/**
	 * 初始化考试类型
	 */
	private void initExamineTypePopupView() {
		btn_series.setOnClickListener(new OnClickListener() {

			@Override
			public void onClick(View v) {
				showListPopupView(v);

			}

			private void showListPopupView(View v) {
				initListPopupView();
				mTypeListPopupView.showAsDropDown(v);

			}

			private void initListPopupView() {
				mTypeListPopupView = new TerminalExameTypeListPopupView(
						TerminalExamActivity.this, mCurrentFirstEntity,
						mSelfActivity, 0, null);

			}
		});
	}

	/**
	 * 初始化考试子类型
	 */
	private void initExamineChildTypePopupView() {
		btn_child_series.setOnClickListener(new OnClickListener() {

			@Override
			public void onClick(View v) {
				showListPopupView(v);

			}

			private void showListPopupView(View v) {
				initListPopupView();
				if (mChildTypeListPopupView != null) {
					mChildTypeListPopupView.showAsDropDown(v);
				}
			}

			private void initListPopupView() {

				if (mCurrentFirstEntity == null) {// 不选择资料类别
					Toast.makeText(mSelfActivity,
							getString(R.string.learning_materials_two_hint),
							Toast.LENGTH_LONG).show();
					return;
				}

				if (mChildTypeListPopupView == null) {
					mChildTypeListPopupView = new TerminalExameTypeListPopupView(
							TerminalExamActivity.this, mCurrentSecondEntity,
							mSelfActivity, 1, mCurrentFirstEntity.id);
				}

			}
		});

	}

	/**
	 * 初始化时间下拉框
	 */
	private void initTimePopupView() {
		btn_time.setOnClickListener(new OnClickListener() {

			@Override
			public void onClick(View v) {
				showListPopupView(v);
			}

			private void showListPopupView(View v) {
				initListPopupView();
				mThirdPopupView.showAsDropDown(v);
			}

			private void initListPopupView() {

				mThirdPopupView = new TerminalExamineTimePopupView(
						TerminalExamActivity.this, mSelectTimeEntity,
						mSelfActivity);

			}
		});

	}

	private void myFindViewById() {
		convertView = findViewById(R.id.lyt_parent);
		recentListView = (ListView) convertView
				.findViewById(R.id.lst_default_list);

		lyt_exam_history = (LinearLayout) findViewById(R.id.lyt_exam_history);
		btn_series = (Button) findViewById(R.id.btn_series);
		btn_child_series = (Button) findViewById(R.id.btn_child_series);
		btn_time = (Button) findViewById(R.id.btn_time);
	//	et_title_input = (EditText) findViewById(R.id.et_title_input);
		et_keyWord_input = (EditText) findViewById(R.id.et_keyWord_input);
		btn_search = (Button) findViewById(R.id.btn_search);

	}

	private void initTitleButtonBar() {
		final TextView titleTv = (TextView) findViewById(R.id.tv_title);
		titleTv.setText(getString(R.string.terminal_examination));

		final ImageButton backBtn = (ImageButton) findViewById(R.id.btn_back);
		backBtn.setOnClickListener(new OnClickListener() {

			@Override
			public void onClick(View v) {
				KeyboardUtil keyboardUtil = new KeyboardUtil();
				keyboardUtil.hideSoftKeyboard(v);
				finish();
			}
		});

	}

	/**
	 * 小类别名称
	 */
	public void initChildTypeBtn(AttrEntity currentFirstEntity) {
		if (currentFirstEntity == null) {
			return;
		}
		final Button childSeriesBooksBtn = (Button) findViewById(R.id.btn_child_series);
		childSeriesBooksBtn.setText(mCurrentSecondEntity.name);
	}

	public void initStudyChildTypeEntity(AttrEntity currentSecondEntity) {
		mCurrentSecondEntity = currentSecondEntity;
	}

	public void initStudyTypeEntity(AttrEntity currentFirstEntity) {
		mCurrentFirstEntity = currentFirstEntity;
	}

	/**
	 * 资料类别
	 * 
	 * @param currentSecondEntity
	 */
	public void initStudyTypeBtn(AttrEntity currentSecondEntity) {
		final Button seriesBooksBtn = (Button) findViewById(R.id.btn_series);
		seriesBooksBtn.setText(mCurrentFirstEntity.name);
	}

	/**
	 * 更新时间实体
	 * 
	 * @param currentThirdEntity
	 */
	public void updateThirdEntity(MessageTopThirdEntity currentThirdEntity) {
		mSelectTimeEntity = currentThirdEntity;
	}

	/**
	 * 更新时间下拉框显示选择的时间
	 * 
	 * @param currentThirdEntity
	 */
	public void updateThirdBtn(MessageTopThirdEntity currentThirdEntity) {
		Button thirdBtn = (Button) findViewById(R.id.btn_time);
		thirdBtn.setText(currentThirdEntity.name);
	}

	/**
	 * 清除小类别已选择值
	 */
	public void clearChildTypeBtn() {
		final Button childSeriesBooksBtn = (Button) findViewById(R.id.btn_child_series);
		childSeriesBooksBtn.setText("");
		mCurrentSecondEntity = null;
		mChildTypeListPopupView = null;
	}

	@Override
	public void onClick(View v) {

	}

	/**
	 * 点击边缘隐藏
	 */
	private void initClickEdgehide() {
		LinearLayout parentLyt = (LinearLayout) findViewById(R.id.lyt_parent);
		parentLyt.setOnClickListener(new OnClickListener() {

			@Override
			public void onClick(View v) {
				// setTopLayoutVisible();
				KeyboardUtil keyboardUtil = new KeyboardUtil();
				keyboardUtil.hideSoftKeyboard(v);
			}
		});
	}

	/**
	 * 点击返回键
	 */
	public boolean onKeyDown(int keyCode, KeyEvent event) {
		if (keyCode == KeyEvent.KEYCODE_BACK && event.getRepeatCount() == 0) {
			/*
			 * if (setTopLayoutVisible()) { return true; }
			 */
			return super.onKeyDown(keyCode, event);
		} else {
			return super.onKeyDown(keyCode, event);
		}
	}
	
	/**
	 * 2016-10-12
	 * 
	 * 终端培训：刷新考试记录
	 * 
	 * @author 390694
	 * 
	 */
	class FreshExaminNumReceiver extends BroadcastReceiver {

		@Override
		public void onReceive(Context context, Intent intent) {
			initExamineHistoryNum();
		}
	}
	
	private void initFreshExaminNumReceiver() {
		mFreshExaminNumReceiver = new FreshExaminNumReceiver();
		IntentFilter filter = new IntentFilter(FRESH_EXAMINE_NUM_ACTION);
		registerReceiver(mFreshExaminNumReceiver, filter);
	}

	@Override
	protected void onDestroy() {
		if (mFreshExaminNumReceiver != null) {
			unregisterReceiver(mFreshExaminNumReceiver);
		}
		super.onDestroy();
	}

}
